
package com.be.beadmin.device.impl;

import cn.hutool.core.util.ObjectUtil;

import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.device.entity.*;
import com.be.beadmin.device.repository.SpareInfoRepository;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.service.service.SerialNumberService;
import lombok.RequiredArgsConstructor;
import com.be.beadmin.device.mapper.SpareFileMapperEx;
import com.be.beadmin.device.repository.SpareFileRepository;
import com.be.beadmin.device.service.SpareFileService;
import com.be.beadmin.device.dto.input.SpareFileDto;
import com.be.beadmin.device.dto.output.SpareFileEx;
import com.be.beadmin.device.dto.input.SpareFileQueryCriteria;
import com.be.beadmin.device.mapper.SpareFileMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Order;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
* @description 服务实现
* @author zty
* @date 2023-10-17
**/
@Service
@RequiredArgsConstructor
public class SpareFileServiceImpl implements SpareFileService {

    @Autowired
    private  SpareFileRepository spareFileRepository;
    @Autowired
    private  SpareFileMapper spareFileMapper;
    @Autowired
    private  SpareFileMapperEx spareFileExMapper;
    @Autowired
    private SpareInfoRepository spareInfoRepository;
    @Resource
    private SerialNumberService serialNumberService;

    MinioUtil minioUtil = new MinioUtil();

    @Override
    public Page<SpareFileEx> getSpareFileByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<SpareFile> page = spareFileRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(SpareFile_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(SpareFile_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<SpareFileEx> page1 = page.map(spareFileExMapper::toEntity);
            return page1;

    }

    @Override
    public void addSpareFile(SpareFileDto spareFileDto) {
            SpareFile result = spareFileRepository.findSpareFileByIdAndDelete(spareFileDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("SpareFile不存在,请重新查询");
            }
            SpareFile spareFile = spareFileMapper.toEntity(spareFileDto);
            spareFileRepository.save(spareFile);
    }

    @Override
    public void updateSpareFile(SpareFileDto spareFileDto) {
            SpareFile spareFile = spareFileRepository.findSpareFileById(spareFileDto.getId());
            spareFile = spareFileMapper.toEntity(spareFileDto);
            spareFileRepository.save(spareFile);
    }


    @Override
    public void delSpareFile(String id) {
        SpareFile spareFile = spareFileRepository.findSpareFileById(id);
        spareFile.setDelete(1);
        spareFileRepository.save(spareFile);
    }

    @Override
    public void delSpareFiles (List<String> ids) { }

    @Override
    public void uploadSpareFile(String spareinfoId, MultipartFile[] multipartFiles, String fileName, String bucketName) throws Exception {
        SpareInfo spareInfo = spareInfoRepository.findSpareInfoByIdAndDelete(spareinfoId , 0);
        //对文件进行操作
        for(MultipartFile multipartFile:multipartFiles) {
            SpareFile spareFile = new SpareFile();
            //文件名

            if (fileName == null || fileName.equals("")) {
                fileName = multipartFile.getOriginalFilename();
            }
            spareFile.setFileName(fileName);

            //判断同一个项目是否有相同的文件名
            int f = spareFileRepository.countSpareFilesByFileNameAndSpareNameAndDelete(fileName, spareInfo.getSpareName(), 0);

            //文件后缀
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
            spareFile.setFileExtEndDate(ext);

            String version;
            while (true) {
                version = "v1." + f;
                int num = spareFileRepository.countSpareFilesByFileNameAndVersionAndDelete(fileName, version, 0);
                if (num == 0) {
                    break;
                } else {
                    f++;
                }
            }
            spareFile.setVersion(version);

            //文件大小
            BigDecimal fileSize = new BigDecimal(multipartFile.getSize());
            spareFile.setFileSize(fileSize);
            //流水号
            String fileCode = serialNumberService.getNextSnByCode("FileCode");
            spareFile.setFileCode(fileCode);
            //项目id
            spareFile.setSpareinfoId(spareinfoId);
            //项目名称
            spareFile.setSpareName(spareInfo.getSpareName());
            //检查单号
            spareFile.setSpareId(spareInfo.getSpareId());
            //设置bucketName
            spareFile.setBucketName(bucketName);
            //处理文件

            String newFileName = fileName.substring(0, fileName.lastIndexOf(".")) + "-" + version + "." + ext;
            String fileUrl = minioUtil.uploadFile3(multipartFile, bucketName, newFileName);
            spareFile.setFileUrl(fileUrl);
            spareFile.setNewFileName(newFileName);
            spareFileRepository.save(spareFile);
        }
        
    }
}